#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void Worker(int number)
{
  int cnt = 10;
  while(cnt)
  {
    printf("I am child process, pid: %d, ppid: %d, cnt: %d, number: %d\n",getpid(), getppid(), cnt--, number);
    sleep(1);
  }
}

const int n = 10;


int main()
{

  for(int i = 0; i < n; i++)
  {
    pid_t id = fork();
    if(id == 0)
    {
      Worker(i);
      exit(0);
    }
  }

  for(int i = 0; i < n; i++)
  {
    int status = 0;
    pid_t rid = waitpid(-1, &status, 0);//pid>0, -1任意一个退出的子进程
    if(rid > 0)
    {
      printf("wait child %d success, exit code: %d\n", rid, WEXITSTATUS(status));
    }
  }














  //for(int i = 0; i < n; i++)
  //{
  //  pid_t id = fork();
  //  if(id == 0)
  //  {
  //    //child
  //    Worker();
  //    exit(0);
  //  }
  //  else{
  //    sleep(10);
  //    //father
  //    printf("wait before\n");
  //    int status = 0;
  //    pid_t rid = waitpid(id, &status, 0);

  //    printf("wait after\n");

  //    if(rid == id)
  //    {
  //      //不能对status整体使用
  //      printf("wait success, pid: %d, rpid: %d, exit sig: %d, exit code: %d\n", getpid(), rid, status&0x7F, (status>>8)&0xFF);
  //    }

  //  }
  //}
  
  //printf("you can see me!");
  //sleep(3);
  //exit(1);

  return 21;
}

